package com.hsj.goldstore.mvp.view.fragment;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.hsj.goldstore.R;
import com.hsj.goldstore.base.BaseMvpFrament;
import com.hsj.goldstore.base.PresenterFactory;
import com.hsj.goldstore.base.PresenterLoader;
import com.hsj.goldstore.bean.LoginBean;
import com.hsj.goldstore.comm.ConstantType;
import com.hsj.goldstore.mvp.present.fragment.MyPresent;
import com.hsj.goldstore.mvp.view.BuyRecordAcitivy;
import com.hsj.goldstore.mvp.view.LoginActivity;
import com.hsj.goldstore.mvp.view.ModifyPasswordActivity;
import com.hsj.goldstore.mvp.view.MyCouponActivity;
import com.hsj.goldstore.mvp.view.MyGoodsActivity;
import com.hsj.goldstore.utils.ActivityCollector;
import com.hsj.goldstore.utils.FileUtil;
import com.hsj.goldstore.utils.Helper;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import de.hdodenhof.circleimageview.CircleImageView;

import static android.app.Activity.RESULT_OK;

/**
 * Created by Administrator on 2018/3/25.
 */

public class MyFragment extends BaseMvpFrament<MyPresent, MyView> implements MyView {

    @BindView(R.id.iv_head)
    CircleImageView ivHead;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.rl_head)
    RelativeLayout rlHead;
    @BindView(R.id.tv_coupon_number)
    TextView tvCouponNumber;
    @BindView(R.id.ll_coupon)
    LinearLayout llCoupon;
    @BindView(R.id.tv_score_number)
    TextView tvScoreNumber;
    @BindView(R.id.ll_score)
    LinearLayout llScore;
    @BindView(R.id.tv_my_goods_number)
    TextView tvMyGoodsNumber;
    @BindView(R.id.ll_my_goods)
    LinearLayout llMyGoods;
    @BindView(R.id.tv_buy_record)
    TextView tvBuyRecord;
    @BindView(R.id.tv_modify_pwd)
    TextView tvModifyPwd;
    @BindView(R.id.tv_help)
    TextView tvHelp;
    @BindView(R.id.tv_exit_login)
    TextView tvExitLogin;
    Unbinder unbinder;
    private static final String TAG = "MyFragment";
    private static final int CAMARA_CODE = 100;
    private static final int CROP_PHOTO = 101;
    private static final int CHOOSE_PHOTO = 102;
    private static final int PEMISSIN_CAMARA = 1000;
    @Override
    protected int getResouseId() {
        return R.layout.fragment_my;
    }

    @Override
    protected void initView() {

        ivHead.setImageResource(R.mipmap.ic_head);
    }

    @Override
    protected void initData() {

        presenter.getUserInfo();
    }

    @Override
    public Loader<MyPresent> onCreateLoader(int id, Bundle args) {
        return new PresenterLoader<>(getActivity(), new PresenterFactory<MyPresent>() {
            @Override
            public MyPresent create() {
                return new MyPresent();
            }
        });
    }


    @Override
    public void initInfo(LoginBean loginBean) {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
    /**
     * 清楚缓存对话框
     */
    private void showChoosePhotoDialog() {
        View view = LayoutInflater.from(getActivity())
                .inflate(R.layout.dialog_choose_photo, null);
        TextView btnCamare = (TextView) view.findViewById(R.id.btn_camare);
        TextView btnAlm = (TextView) view.findViewById(R.id.btn_alm);
        TextView btnCancel = (TextView) view.findViewById(R.id.btn_cancel);

        final Dialog photoDialog = new Dialog(getActivity()
                , R.style.MyProgressDialog);
        photoDialog.setContentView(view);
        photoDialog.setCancelable(true);
        photoDialog.setCanceledOnTouchOutside(true);
        photoDialog.show();
        Window mWindow = photoDialog.getWindow();
        mWindow.setGravity(Gravity.BOTTOM);
        btnCamare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isCamare = true;
                //6.0以上系统需要 运行时权限
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    check();
                } else {
                    pickPhotoFromCamera();
                }
                photoDialog.dismiss();
            }
        });
        btnAlm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isCamare = false;
                //6.0以上系统需要 运行时权限
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    check();
                } else {
                    pickPhotoFromAlbm();
                }
                photoDialog.dismiss();
            }
        });
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                photoDialog.dismiss();
            }
        });
    }



    /**
     * 裁剪图片
     */
    private void cropPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        //读写授权
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, CROP_PHOTO);
    }

    private Uri imageUri;
    private File outImageFile;

    /**
     * 从相机获取图片
     */
    private void pickPhotoFromCamera() {
        //用于保存调用相机拍照后所生成的文件
        outImageFile = new File(Environment.getExternalStorageDirectory(),
                System.currentTimeMillis() + ".jpg");
        try {
            if (outImageFile.exists()) {
                outImageFile.delete();
            }
            outImageFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //跳转到调用系统相机
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        imageUri = Uri.fromFile(outImageFile);
        //判断版本 如果在Android7.0以上,使用FileProvider获取Uri
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(getActivity(),
                    "com.hsj.goldstore", outImageFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
        } else {    //否则使用Uri.fromFile(file)方法获取Uri
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        }
        startActivityForResult(intent, CAMARA_CODE);
    }
    /**
     * 从相册获取图片
     */
    private void pickPhotoFromAlbm() {
        Intent pickIntent = new Intent(Intent.ACTION_PICK, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
        pickIntent.setType("image/*");
        startActivityForResult(pickIntent, CHOOSE_PHOTO);
    }
    private List<String> permissionList;
    private void check() {
        //第一步检查是否有权限
        permissionList = new ArrayList<>();
        if (isCamare&&ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.CAMERA);
        }
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        }
        //有权限未申请
        if (!permissionList.isEmpty()) {
            //第一次申请权限，如果用户拒绝，下次申请需向用户解释为什么要这个权限
            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                    permissionList.get(0))) {
                new AlertDialog.Builder(getActivity())
                        .setMessage("设置头像需要权限")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //申请权限
                                ActivityCompat.requestPermissions(getActivity(),
                                        permissionList.toArray(new String[permissionList.size()]), PEMISSIN_CAMARA);
                            }
                        })
                        .show();
            } else {
                ActivityCompat.requestPermissions(getActivity(),
                        permissionList.toArray(new String[permissionList.size()]), PEMISSIN_CAMARA);
            }
        } else {
            //权限都已经申请
            if (isCamare) {
                pickPhotoFromCamera();
            } else {
                pickPhotoFromAlbm();
            }
        }

    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PEMISSIN_CAMARA) {
            if (grantResults.length > 0) {
                for (int grantReuslt : grantResults) {
                    if (grantReuslt != PackageManager.PERMISSION_GRANTED) {
                        Helper.showToast(getActivity(), "权限已被禁止,请到设置处打开权限");
                        return;
                    }
                }
                if (isCamare) {
                    pickPhotoFromCamera();
                } else {
                    pickPhotoFromAlbm();
                }
            }
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            // 调用相机后返回
            case CAMARA_CODE:
                if (resultCode == RESULT_OK) {
                    //用相机返回的照片去调用剪裁也需要对Uri进行处理
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        Uri contentUri = FileProvider.getUriForFile(getActivity(),
                                "com.hsj.goldstore", outImageFile);
                        cropPhoto(contentUri);//裁剪图片
                    } else {
                        cropPhoto(imageUri);//裁剪图片
                    }
                }
                break;
            //调用相册后返回
            case CHOOSE_PHOTO:
                if (resultCode == RESULT_OK) {
                    Uri uri = data.getData();
                    //裁剪图片
                    cropPhoto(uri);
                }
                break;
            //调用剪裁后返回
            case CROP_PHOTO:
                if (resultCode != RESULT_OK) {
                    return;
                }

                Bundle resultBundle = data.getExtras();
                if (resultBundle != null) {
                    //在这里获得了剪裁后的头像
                    Bitmap image = resultBundle.getParcelable("data");

                    if (null != image) {
                        //保存图片
                        String path = FileUtil.saveFile(getActivity(), System.currentTimeMillis() + ".jpg", image);
                        Log.d(TAG, "head_path: " + path);
                        //设置到头像
                        Glide.with(getActivity())
                                .load(new File(path))
                                .into(ivHead);
                    }
                }
                break;
        }
    }

    private boolean isCamare = false;
    @OnClick({R.id.iv_head, R.id.tv_name, R.id.ll_coupon, R.id.ll_my_goods, R.id.tv_buy_record, R.id.tv_modify_pwd, R.id.tv_help, R.id.tv_exit_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_head:
                    showChoosePhotoDialog();
                break;
            case R.id.tv_name:

                break;
            case R.id.ll_coupon:
                MyCouponActivity.getIntantce(getActivity(), MyCouponActivity.class);
                break;
            case R.id.ll_my_goods:
                MyGoodsActivity.getIntantce(getActivity(), MyGoodsActivity.class);
                break;
            case R.id.tv_buy_record:
                BuyRecordAcitivy.getIntantce(getActivity(), BuyRecordAcitivy.class);
                break;
            case R.id.tv_modify_pwd:
                ModifyPasswordActivity.getIntantce(getActivity(), ModifyPasswordActivity.class);
                break;
            case R.id.tv_help:
                break;
            case R.id.tv_exit_login:
                //清除个人数据
                SharedPreferences.Editor editor = getActivity().getSharedPreferences(ConstantType.SP_USER, Activity.MODE_PRIVATE).edit();
                editor.clear();
                LoginActivity.getIntance(getActivity(), null);
                getActivity().finish();
                break;
        }
    }



}
